package org.teremail.util;

import java.util.HashMap;
import java.util.Map;

/**
 * Simple cache for items that need to be stored in a thread local object.
 * Useful for things like date formats that aren't thread safe.
 * 
 * @author Michael Barker
 *
 * @param <K> The key into the cache
 * @param <V> The value to be cached
 */
public abstract class ThreadLocalCache<K,V> extends ThreadLocal<Map<K,V>> {

    @Override
    protected Map<K, V> initialValue() {
        return new HashMap<K, V>();
    }
    
    public V getValue(K k) {
        Map<K, V> cache = get();
        V v = cache.get(k);
        if (v == null) {
            v = create(k);
            cache.put(k, v);
        }
        return v;
    }
    
    public abstract V create(K k);
}
